//
//  ServerRequestTool.m
//  NewJiaZheng
//
//  Created by lianjie on 2017/12/1.
//  Copyright © 2017年 kangbinbin. All rights reserved.
//

#import "ServerRequestTool.h"
#import "CheckNetwork.h"
#import "NetworkError.h"

//static AFHTTPSessionManager *manager;

@implementation ServerRequestTool



//为了防止内存泄露
+ (AFHTTPSessionManager *)sharedHttpSession
{
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 10;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/plain", @"text/json", @"text/javascript", @"text/html", nil];
//    });
    return manager;
}

///GET请求方式：请求类型为JSON类型；返回类型为JSON类型；编码方式为：@“application/x-www-form-urlencoded; charset=utf-8”
+ (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success control:(UIViewController *)ctrl
{
    NSString *url = [NSString stringWithFormat:@"%@%@",Server_IP,URLString];
    if ([CheckNetwork isExistenceNetwork]) {
        AFHTTPSessionManager *manager = [ServerRequestTool sharedHttpSession];
        
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"11"]) {
                    
                    ///没有权限访问
                    
                    [ctrl showHint:@"登录权限失效"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        UIViewController *loginVC = [[NSClassFromString(@"LoginViewController") alloc]init];
                        
                        
                        [ctrl presentViewController:loginVC animated:YES completion:nil];
                        
                        
                    });
                    
                    
                }else if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"0"]){
                    
                    success(responseObject);
                }else{
                    
                    [ctrl showHint:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
                
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            VTLog(@"错误信息提示：--------%@",error);
            [ctrl showHint:@"服务中断,稍后再试"];
            [ctrl hideHud:YES];
        }];
        
    }else{
        [ctrl showHint:[NetworkError errorMessageWithCode:WKNertworkNotConnectInternet]];
        
        [ctrl hideHud:YES];
        
    }
}


///POST请求方式：请求类型为JSON类型；返回类型为JSON类型；编码方式为：@“application/x-www-form-urlencoded; charset=utf-8”




+(void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success control:(UIViewController *)ctrl
{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Server_IP,URLString];
    
    VTLog(@"IP地址====%@ ，参数===%@",url,parameters);
    
    if ([CheckNetwork isExistenceNetwork]) {
        
        AFHTTPSessionManager *manager = [ServerRequestTool sharedHttpSession];
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [ctrl hideHud:YES];
            if (success) {
                
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"11"]) {
                    
                    ///没有权限访问
                    
                    [ctrl showHint:@"登录权限失效"];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        UIViewController *loginVC = [[NSClassFromString(@"LoginViewController") alloc]init];
                        
//                        MainNavController *nav = [[MainNavController alloc]initWithRootViewController:loginVC];
                        
                        
                        [ctrl presentViewController:loginVC animated:YES completion:nil];
                        
                        
                    });
                    
                    
                    
                }else if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"0"]){
                    
                    success(responseObject);
                }else{
                    
                    
                    [ctrl showHint:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
                
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            VTLog(@"错误信息提示：--------%@",error);
            [ctrl showHint:@"服务中断,稍后再试"];
            [ctrl hideHud:YES];
        }];
        
    }else{
        [ctrl showHint:[NetworkError errorMessageWithCode:WKNertworkNotConnectInternet]];
        
        [ctrl hideHud:YES];
        
    }
}



+(void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failureCode:(void (^)(id))failureCode control:(UIViewController *)ctrl
{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Server_IP,URLString];
    
    VTLog(@"IP地址====%@ ，参数===%@",url,parameters);
    
    if ([CheckNetwork isExistenceNetwork]) {
        
        AFHTTPSessionManager *manager = [ServerRequestTool sharedHttpSession];
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [ctrl hideHud:YES];
            if (success) {
                
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"11"]) {
                    
                    ///没有权限访问
                    
                    [ctrl showHint:@"登录权限失效"];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        UIViewController *loginVC = [[NSClassFromString(@"LoginViewController") alloc]init];
                        
                        //                        MainNavController *nav = [[MainNavController alloc]initWithRootViewController:loginVC];
                        
                        
                        [ctrl presentViewController:loginVC animated:YES completion:nil];
                        
                        
                    });
                    
                    
                    
                }else if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"0"]){
                    
                    success(responseObject);
                }else{
                    
                    
//                    failureCode(responseObject);
                    [ctrl showHint:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
                
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            VTLog(@"错误信息提示：--------%@",error);
            [ctrl showHint:@"服务中断,稍后再试"];
            [ctrl hideHud:YES];
        }];
        
    }else{
        [ctrl showHint:[NetworkError errorMessageWithCode:WKNertworkNotConnectInternet]];
        
        [ctrl hideHud:YES];
        
    }
}



+(void)POST:(NSString *)URLString parametersJSON:(id)parameters success:(void (^)(id))success control:(UIViewController *)ctrl
{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Server_IP,URLString];
    
    VTLog(@"IP地址====%@ ，参数===%@",url,parameters);
    
    if ([CheckNetwork isExistenceNetwork]) {
        
        AFHTTPSessionManager *manager = [ServerRequestTool sharedHttpSession];
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        
        [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [ctrl hideHud:YES];
            if (success) {
                
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"11"]) {
                    
                    ///没有权限访问
                    
                    [ctrl showHint:@"登录权限失效"];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        UIViewController *loginVC = [[NSClassFromString(@"LoginViewController") alloc]init];
                        
                        //                        MainNavController *nav = [[MainNavController alloc]initWithRootViewController:loginVC];
                        
                        
                        [ctrl presentViewController:loginVC animated:YES completion:nil];
                        
                        
                    });
                    
                    
                    
                }else if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"0"]){
                    
                    success(responseObject);
                }else{
                    
                    [ctrl showHint:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
                
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            VTLog(@"错误信息提示：--------%@",error);
            [ctrl showHint:@"服务中断,稍后再试"];
            [ctrl hideHud:YES];
        }];
        
    }else{
        [ctrl showHint:[NetworkError errorMessageWithCode:WKNertworkNotConnectInternet]];
        
        [ctrl hideHud:YES];
        
    }
}

#pragma mark ----上传单张图片
+(void)uploadImageWithPath:(NSString *)path image:(UIImage *)image params:(NSDictionary *)params success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure control:(UIViewController *)ctrl
{
    NSArray *array = [NSArray arrayWithObject:image];
    [self uploadImageWithPath:path photos:array params:params success:success failure:failure control:ctrl];
}


#pragma mark 上传图片
+ (void)uploadImageWithPath:(NSString *)path photos:(NSArray *)photos params:(NSDictionary *)params success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure control:(UIViewController *)ctrl
{
        [ctrl showIndicatorHint:@"正在上传,请稍等."];
        NSString *strUrl = [NSString stringWithFormat:@"%@%@",Server_IP,path];
    if ([CheckNetwork isExistenceNetwork]) {
        AFHTTPSessionManager *manager = [ServerRequestTool sharedHttpSession];
        
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        [manager POST:strUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            for (int i = 0; i < photos.count; i ++) {
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmss";
                NSString *str=[formatter stringFromDate:[NSDate date]];
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                UIImage *image = photos[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5f);
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"upload%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            VTLog(@"uploadProgress is %lld,总字节 is %lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [ctrl hideHud:YES];
            NSString *resultCode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]];
//            NSString *resultInfo = [responseObject objectForKey:@"result_info"];
            VTLog(@"resultInfo is %@",responseObject);
            if ([resultCode isEqualToString:@"0"]) {
                [ctrl showHint:@"上传成功"];
                if (success == nil) return ;
                success(responseObject);
            }else {
                [ctrl showHint:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                if (failure == nil) return ;
                failure();
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            VTLog(@"图片上传失败====%@",error);
            [ctrl hideHud:YES];
            [ctrl showHint:@"上传失败"];
            if (failure == nil) return ;
            failure();
        }];
//    error    NSError *    domain: @"com.alamofire.error.serialization.response" - code: 18446744073709550605    0x000060000064fd50
    }else{
        [ctrl showHint:[NetworkError errorMessageWithCode:WKNertworkNotConnectInternet]];
        
        [ctrl hideHud:YES];
        
    }
    
}



@end
